package com.omdbapi;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Logger;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.ziplock.IO;

class RestClient {
    private static final String OMDBURL = "http://www.omdbapi.com/";

    private static String asString(HttpResponse execute) throws IOException {
	if (execute == null || execute.getEntity() == null)
	    return "";
	final InputStream in = execute.getEntity().getContent();
	try {
	    return IO.slurp(in);
	} finally {
	    in.close();
	}
    }

    private static String join(String delimiter, Object... collection) {
	if (collection.length == 0) {
	    return "";
	}
	StringBuilder sb = new StringBuilder();
	for (Object obj : collection) {
	    sb.append(obj).append(delimiter);
	}
	return sb.substring(0, sb.length() - delimiter.length());
    }

    private static URI normalize(URI uri, Object... path) {
	return URI.create(uri.toASCIIString() + "?" + join("&", path)).normalize();
    }

    private final Logger logger = Logger.getLogger("omdb");

    private String execute(HttpRequestBase request) throws IOException {
	logger.info("executing " + request.toString());
	final HttpClient client = new DefaultHttpClient();
	final HttpResponse response = client.execute(request);

	final int code = response.getStatusLine().getStatusCode();
	final String message = asString(response);

	if (code < 200 || code >= 300) {
	    throw new RuntimeException(response.getStatusLine().toString() + " - " + message);
	}

	return message;
    }

    private String executeWithProxy(HttpRequestBase request) throws IOException {
	logger.info("executing " + request.toString());

	HttpHost proxy = new HttpHost("isprxsrv", 8080, "http");

	DefaultHttpClient httpclient = new DefaultHttpClient();
	String message = "";
	try {
	    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

	    System.out.println("executing request to " + request + " via " + proxy);
	    HttpResponse response = httpclient.execute(request);

	    final int code = response.getStatusLine().getStatusCode();
	    message = asString(response);

	    if (code < 200 || code >= 300) {
		throw new RuntimeException(response.getStatusLine().toString() + " - " + message);
	    }

	} finally {
	    // When HttpClient instance is no longer needed,
	    // shut down the connection manager to ensure
	    // immediate deallocation of all system resources
	    httpclient.getConnectionManager().shutdown();
	}

	return message;
    }

    public String get(Object... path) throws IOException, URISyntaxException {
	return execute(new HttpGet(normalize(new URI(OMDBURL), path)));
	// return executeWithProxy(new HttpGet(normalize(new URI(OMDBURL), path)));
    }
}